package com.example.lib_core.util

import android.app.Activity
import android.app.Dialog
import android.util.Log
import android.view.View
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import com.example.lib_core.util.presenter.GlobalLayoutListenerTask
import java.util.*

object KeyBoardEventBus {

    private val taskCache: Hashtable<Any,GlobalLayoutListenerTask> = Hashtable()

    /**
     * 用于注册键盘监听，此方法适用于 View、Dialog、Fragement、FragementActivity、Activity
     *
     * @param obj 需要监听的类（）
     */
    fun register(obj: Any?){
        val activity = getActivity(obj)
        if (activity == null){
            debug("register时获取activity失败！")
            return
        }
        register(activity, obj)
    }

    /**
     * 此方法区别于 {@link #register(Object)} ,之前的方法会限制注册的类型，当前的不会限制类型
     *
     * @param activity 宿主activity
     * @param obj   监听的类
     */
    fun register(activity: Activity, obj: Any?){
        if (obj == null) {
            debug("object为null!")
            return
        }
        var task = taskCache[activity]
        if (task == null){
            task = GlobalLayoutListenerTask(activity)
        }
        task.addCallBack(obj)
        if (!task.isEmpty()) task.start()
        taskCache[activity] = task
    }

    /**
     * 反注册
     *
     * @param obj 取消监听的类
     */
    fun unRegister(obj: Any?){
        //获取失败则直接停止，反之进行反注册
        val activity = getActivity(obj)
        if (activity == null){
            debug("unRegister时获取activity失败")
            return
        }
        unRegister(activity, obj)
    }

    /**
     * 反注册
     *
     * @param activity 宿主activity
     * @param obj 监听的类
     */
    fun unRegister(activity: Activity, obj: Any?){
        if ( obj == null) {
            debug("activity或object为null!")
            return
        }
        val task = taskCache[activity] ?: return
        task.removeCallback(obj)
        if (task.isEmpty()){
            task.cancel()
            taskCache.remove(task)
        }
    }

    /**
     * 获取对应View、Dialog、Fragment、FragmentActivity、Activity
     * (如果Object为null或者不是支持的类型则返回null)
     *
     * @param obj 需要获取的类
     * @return 返回对应的activity
     */
    private fun getActivity(obj: Any?): Activity?{
        if (obj == null) return null

        return when(obj){
            is View -> obj.context as Activity
            is Dialog -> obj.context as Activity
            is Fragment -> obj.activity
            is FragmentActivity -> obj
            is Activity -> obj
            else -> null
        }
    }

    /**
     * 用于打印信息
     *
     * @param msg 待打印的内容
     */
    private fun debug(msg: String){
        Log.e("KeyBoardEventBus",msg)
    }
}